﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace CoffeeInventory
{
	public partial class SupplierPage
	{
	    private bool _searchEntry;
	    private readonly CollectionViewSource _suppliersViewSource;
		public SupplierPage()
		{
			InitializeComponent();
		    _suppliersViewSource = (CollectionViewSource) FindResource("suppliersViewSource");
		}

		private void AddSupplierButtonClick(object sender, RoutedEventArgs e)
		{
			var addSupplierWindow = new AddSupplierWindow();
			addSupplierWindow.ShowDialog();
            Refresh();
		}

        private void TextBoxGotFocus(object sender, RoutedEventArgs e)
        {
            if (!_searchEntry)
            {
                _searchEntry = true;
                _search.Text = string.Empty;
                _clearSearch.Visibility = Visibility.Visible;
            }
        }

        private void SearchLostFocus(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrWhiteSpace(_search.Text))
            {
                _searchEntry = false;
            }
            if (!_searchEntry)
            {
                _search.Text = "search";
                _clearSearch.Visibility = Visibility.Collapsed;
            }
        }

        private void ClearSearchClick(object sender, RoutedEventArgs e)
        {
            _searchEntry = false;
            _search.Text = "search";
            _clearSearch.Visibility = Visibility.Collapsed;
        }

        private void SearchTextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                Refresh();
            }
            catch
            {
                
            }
        }

        private void Refresh()
        {
            var context = new DBModelContainer();
            if (_searchEntry && !String.IsNullOrWhiteSpace(_search.Text))
            {
                _suppliersViewSource.Source = GetSuppliers(context, _search.Text);
            }
            else
            {
                _suppliersViewSource.Source = GetSuppliers(context);
            }
        }

	    private void PageLoaded(object sender, RoutedEventArgs e)
        {
            Refresh();
        }
        private IQueryable<Supplier> GetSuppliers(DBModelContainer dBModelContainer)
        {
            // Auto generated code
            return dBModelContainer.Suppliers;
        }
        private IQueryable<Supplier> GetSuppliers(DBModelContainer dBModelContainer, string name)
        {
            // Auto generated code
            return dBModelContainer.Suppliers.Where(supplier => supplier.Name.Contains(name));
        }
	}
}